package com.uzai.console.service.alarm.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.enums.MerConfigKeyEnum;
import com.uzai.common.enums.RedisCacheKeyEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.dto.alarm.alarmcontacter.AlarmContacterIdDto;
import com.uzai.console.dto.alarm.alarmcontacter.AlarmContacterInfoDto;
import com.uzai.console.dto.alarm.alarmcontacter.AlarmContacterOpenidDto;
import com.uzai.console.dto.alarm.alarmcontacter.AlarmContacterQuery;
import com.uzai.console.entity.AlarmContacter;
import com.uzai.console.entity.MerBaseConfig;
import com.uzai.console.entity.Merchant;
import com.uzai.console.enums.SmsType;
import com.uzai.console.mapper.AlarmContacterMapper;
import com.uzai.console.mapper.MerBaseConfigMapper;
import com.uzai.console.mapper.MerchantMapper;
import com.uzai.console.service.alarm.AlarmContacterService;
import com.uzai.console.service.wxpub.WxpubService;
import com.uzai.console.vo.alarm.alarmcontacter.AlarmContacterDingdingUrlVo;
import com.uzai.console.vo.alarm.alarmcontacter.AlarmContacterInfoVo;
import com.uzai.console.vo.alarm.alarmcontacter.AlarmContacterOpenidUrlVo;
import com.uzai.console.vo.alarm.alarmcontacter.AlarmContacterOpenidVo;
import com.uzai.console.vo.smscode.SmsCodeVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 紧急联系人
 *
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class AlarmContacterServiceImpl implements AlarmContacterService {

    Logger logger = LoggerFactory.getLogger(AlarmContacterServiceImpl.class);

    @Autowired
    private AlarmContacterMapper alarmContacterMapper;
    @Autowired
    private WxpubService wxpubService;
    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MerBaseConfigMapper merBaseConfigMapper;
    @Autowired
    private MerchantMapper merchantMapper;

    /**
     * 查询紧急联系人列表
     *
     * @param alarmContacterQuery
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public Page<AlarmContacterInfoVo> findAlarmContacterList(AlarmContacterQuery alarmContacterQuery) {
        //新建返回到页面的LIST对象
        List<AlarmContacterInfoVo> alarmContacterPageVoList = new ArrayList<>();

        //执行分页查询对象
        Page<AlarmContacter> page = new Page<>();
        alarmContacterQuery.convert(page);
        ArrayList<AlarmContacter> alarmContacterList = alarmContacterMapper.findByList(page, alarmContacterQuery);
        if (alarmContacterList != null && alarmContacterList.size() > 0) {
            for (AlarmContacter alarmContacter : alarmContacterList) {
                AlarmContacterInfoVo alarmContacterPageVo = new AlarmContacterInfoVo();
                BeanUtils.copyProperties(alarmContacter, alarmContacterPageVo);

                try {
                    //电话转化成list
                    alarmContacterPageVo.setMobileList(JSONObject.parseArray(alarmContacter.getMobile(), String.class));

                    //邮箱转化成list
                    alarmContacterPageVo.setMailList(JSONObject.parseArray(alarmContacter.getMail(), String.class));

                    //openid化成list
                    alarmContacterPageVo.setOpenidList(JSONObject.parseArray(alarmContacter.getOpenid(), String.class));

                    //dingding化成list
                    if (StringUtils.isNotBlank(alarmContacter.getDingding())) {
                        JSONObject dingding = JSONObject.parseObject(alarmContacter.getDingding());
                        if (dingding != null) {
                            //是否@所有人
                            alarmContacterPageVo.setNotifyAll(dingding.getInteger("notifyAll"));
                            //钉钉信息
                            String dingdingStr = dingding.getString("dingdingList");
                            if (StringUtils.isNotBlank(dingdingStr)) {
                                List<AlarmContacterInfoVo.DingDing> dingDingList = JSONObject.parseArray(dingdingStr, AlarmContacterInfoVo.DingDing.class);
                                alarmContacterPageVo.setDingdingList(dingDingList);
                            }
                        }
                    }
                } catch (Exception e) {
                    //JSON解析错误
                    logger.error("JOSN transfer error={}", e.getMessage());
                }

                alarmContacterPageVoList.add(alarmContacterPageVo);
            }
        }

        //返回到页面分页对象
        Page<AlarmContacterInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(alarmContacterPageVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询紧急联系人列表
     *
     * @param alarmContacterQuery
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public List<AlarmContacterInfoVo> findAlarmContacterListSelect(AlarmContacterQuery alarmContacterQuery) {
        //新建返回到页面的LIST对象
        List<AlarmContacterInfoVo> alarmContacterPageVoList = new ArrayList<>();

        //执行分页查询对象
        ArrayList<AlarmContacter> alarmContacterList = alarmContacterMapper.findByList(alarmContacterQuery);
        if (alarmContacterList != null && alarmContacterList.size() > 0) {
            for (AlarmContacter alarmContacter : alarmContacterList) {
                AlarmContacterInfoVo alarmContacterPageVo = new AlarmContacterInfoVo();
                BeanUtils.copyProperties(alarmContacter, alarmContacterPageVo);

                try {
                    //电话转化成list
                    alarmContacterPageVo.setMobileList(JSONObject.parseArray(alarmContacter.getMobile(), String.class));

                    //邮箱转化成list
                    alarmContacterPageVo.setMailList(JSONObject.parseArray(alarmContacter.getMail(), String.class));

                    //openid化成list
                    alarmContacterPageVo.setOpenidList(JSONObject.parseArray(alarmContacter.getOpenid(), String.class));

                    //dingding化成list
                    if (StringUtils.isNotBlank(alarmContacter.getDingding())) {
                        JSONObject dingding = JSONObject.parseObject(alarmContacter.getDingding());
                        if (dingding != null) {
                            //是否@所有人
                            alarmContacterPageVo.setNotifyAll(dingding.getInteger("notifyAll"));
                            //钉钉信息
                            String dingdingStr = dingding.getString("dingdingList");
                            if (StringUtils.isNotBlank(dingdingStr)) {
                                List<AlarmContacterInfoVo.DingDing> dingDingList = JSONObject.parseArray(dingdingStr, AlarmContacterInfoVo.DingDing.class);
                                alarmContacterPageVo.setDingdingList(dingDingList);
                            }
                        }
                    }
                } catch (Exception e) {
                    //JSON解析错误
                    logger.error("JOSN transfer error={}", e.getMessage());
                }

                alarmContacterPageVoList.add(alarmContacterPageVo);
            }
        }

        return alarmContacterPageVoList;
    }

    /**
     * 添加紧急联系人
     *
     * @param alarmContacterInfoDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public void addAlarmContacter(AlarmContacterInfoDto alarmContacterInfoDto) {
        Merchant merchant = merchantMapper.selectById(alarmContacterInfoDto.getMerId());
        if (merchant == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未找到该运营商");
        }

        //查询运营商短信验证功能信息
        boolean smsCodeFlag = true;
        MerBaseConfig merBaseConfig_smsCode = merBaseConfigMapper.selectByMerId(merchant.getId(), MerConfigKeyEnum.SMS_CODE_CONFIG.getValue());
        if (merBaseConfig_smsCode != null) {
            SmsCodeVo smsCodeVo = JSONObject.parseObject(merBaseConfig_smsCode.getVal(), SmsCodeVo.class);
            if (smsCodeVo != null && smsCodeVo.getAlarmContacterSave() == 0) { //不需要认证
                smsCodeFlag = false;
            }
        }

        if (smsCodeFlag) {
            //如果输入的验证码不是系统通用密码，则需要验证
            if (!uzaiConsoleSysConfig.getDefaultPassword().equals(alarmContacterInfoDto.getCode())) {
                //获取存在redis中的验证码
                String codeByRedis = (String) redisTemplate.opsForValue().get(String.format(SmsType.ALARM_EVENT_UPDATE.getDesc(), merchant.getMobile()));
                //判断验证码是否过期
                if (StringUtils.isBlank(codeByRedis)) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_MISS);
                }
                //验证码是否正确
                if (!codeByRedis.equals(alarmContacterInfoDto.getCode()) && !uzaiConsoleSysConfig.getDefaultPassword().equals(alarmContacterInfoDto.getCode())) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_ERR);
                }
                //验证成功，删除验证码
                redisTemplate.delete(String.format(SmsType.ALARM_EVENT_UPDATE.getDesc(), merchant.getMobile()));
            }
        }

        if (StringUtils.isBlank(alarmContacterInfoDto.getName())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入紧急联系人姓名");
        }

        //判断页面是否输入手机号/邮箱/悠哉公众号openid/dingding机器人四项中的任意一项
        Boolean flag = false;
        if (alarmContacterInfoDto.getMobileList() != null && alarmContacterInfoDto.getMobileList().size() > 0) {
            flag = true;
            //验证邮箱格式是否正确
            for (String mobile : alarmContacterInfoDto.getMobileList()) {
                if (!Tools.checkPhone(Tools.getStr(mobile))) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "手机格式不正确：" + mobile);
                }
            }
        }
        if (alarmContacterInfoDto.getMailList() != null && alarmContacterInfoDto.getMailList().size() > 0) {
            flag = true;
            //验证邮箱格式是否正确
            for (String mail : alarmContacterInfoDto.getMailList()) {
                if (!Tools.checkEmail(Tools.getStr(mail))) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "邮箱格式不正确：" + mail);
                }
            }
        }

        if (alarmContacterInfoDto.getOpenidList() != null && alarmContacterInfoDto.getOpenidList().size() > 0) {
            flag = true;
        }

        if (alarmContacterInfoDto.getDingdingList() != null && alarmContacterInfoDto.getDingdingList().size() > 0) {
            flag = true;
        }

        if (!flag) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "至少输入手机号/邮箱/悠哉公众号openid/dingding机器人四项中的任意一项");
        }

        AlarmContacter alarmContacter = new AlarmContacter();
        BeanUtils.copyProperties(alarmContacterInfoDto, alarmContacter);

        if (alarmContacterInfoDto.getMobileList() != null && alarmContacterInfoDto.getMobileList().size() > 0) {
            alarmContacter.setMobile(Tools.getStrEmpty(JSONObject.toJSONString(alarmContacterInfoDto.getMobileList())));
        }

        if (alarmContacterInfoDto.getMailList() != null && alarmContacterInfoDto.getMailList().size() > 0) {
            alarmContacter.setMail(Tools.getStrEmpty(JSONObject.toJSONString(alarmContacterInfoDto.getMailList())));
        }

        if (alarmContacterInfoDto.getOpenidList() != null && alarmContacterInfoDto.getOpenidList().size() > 0) {
            alarmContacter.setOpenid(Tools.getStrEmpty(JSONObject.toJSONString(alarmContacterInfoDto.getOpenidList())));
        }

        //封装dingding
        JSONObject jsonObject = new JSONObject();
        if (alarmContacterInfoDto.getDingdingList() != null && alarmContacterInfoDto.getDingdingList().size() > 0) {
            jsonObject.put("dingdingList", JSONObject.toJSONString(alarmContacterInfoDto.getDingdingList()));
        }
        jsonObject.put("notifyAll", alarmContacterInfoDto.getNotifyAll());
        alarmContacter.setDingding(jsonObject.toJSONString());

        Integer now = DateUtil.getNowTime();
        alarmContacter.setId(IdWorker.getId());
        alarmContacter.setCreateTime(now);
        alarmContacter.setUpdateTime(now);
        alarmContacterMapper.insert(alarmContacter);
    }

    /**
     * 修改紧急联系人
     *
     * @param alarmContacterInfoDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public void updateAlarmContacter(AlarmContacterInfoDto alarmContacterInfoDto) {

        Merchant merchant = merchantMapper.selectById(alarmContacterInfoDto.getMerId());
        if (merchant == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未找到该运营商");
        }

        //查询运营商短信验证功能信息
        boolean smsCodeFlag = true;
        MerBaseConfig merBaseConfig_smsCode = merBaseConfigMapper.selectByMerId(merchant.getId(), MerConfigKeyEnum.SMS_CODE_CONFIG.getValue());
        if (merBaseConfig_smsCode != null) {
            SmsCodeVo smsCodeVo = JSONObject.parseObject(merBaseConfig_smsCode.getVal(), SmsCodeVo.class);
            if (smsCodeVo != null && smsCodeVo.getAlarmContacterSave() == 0) { //不需要认证
                smsCodeFlag = false;
            }
        }

        if (smsCodeFlag) {
            //如果输入的验证码不是系统通用密码，则需要验证
            if (!uzaiConsoleSysConfig.getDefaultPassword().equals(alarmContacterInfoDto.getCode())) {
                //获取存在redis中的验证码
                String codeByRedis = (String) redisTemplate.opsForValue().get(String.format(SmsType.ALARM_EVENT_UPDATE.getDesc(), merchant.getMobile()));
                //判断验证码是否过期
                if (StringUtils.isBlank(codeByRedis)) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_MISS);
                }
                //验证码是否正确
                if (!codeByRedis.equals(alarmContacterInfoDto.getCode()) && !uzaiConsoleSysConfig.getDefaultPassword().equals(alarmContacterInfoDto.getCode())) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_ERR);
                }
                //验证成功，删除验证码
                redisTemplate.delete(String.format(SmsType.ALARM_EVENT_UPDATE.getDesc(), merchant.getMobile()));
            }
        }

        if (alarmContacterInfoDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        if (StringUtils.isBlank(alarmContacterInfoDto.getName())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入紧急联系人姓名");
        }

        //判断页面是否输入手机号/邮箱/悠哉公众号openid/dingding机器人四项中的任意一项
        Boolean flag = false;
        if (alarmContacterInfoDto.getMobileList() != null) {
            flag = true;
            //验证邮箱格式是否正确
            for (String mobile : alarmContacterInfoDto.getMobileList()) {
                if (!Tools.checkPhone(Tools.getStr(mobile))) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "手机格式不正确：" + mobile);
                }
            }

        }
        if (alarmContacterInfoDto.getMailList() != null) {
            flag = true;
            //验证邮箱格式是否正确
            for (String mail : alarmContacterInfoDto.getMailList()) {
                if (!Tools.checkEmail(Tools.getStr(mail))) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "邮箱格式不正确：" + mail);
                }
            }
        }
        if (alarmContacterInfoDto.getOpenidList() != null && alarmContacterInfoDto.getOpenidList().size() > 0) {
            flag = true;
        }

        if (alarmContacterInfoDto.getDingdingList() != null && alarmContacterInfoDto.getDingdingList().size() > 0) {
            flag = true;
        }

        if (!flag) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "至少输入手机号/邮箱/悠哉公众号openid/dingding机器人四项中的任意一项");
        }

        AlarmContacter alarmContacter = alarmContacterMapper.selectById(alarmContacterInfoDto.getId(), alarmContacterInfoDto.getMerId());

        if (alarmContacter == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该紧急联系人不存在");
        }

        alarmContacter.setName(alarmContacterInfoDto.getName());
        alarmContacter.setMobile(Tools.getStrEmpty(JSONObject.toJSONString(alarmContacterInfoDto.getMobileList())));
        alarmContacter.setMail(Tools.getStrEmpty(JSONObject.toJSONString(alarmContacterInfoDto.getMailList())));
        alarmContacter.setOpenid(Tools.getStrEmpty(JSONObject.toJSONString(alarmContacterInfoDto.getOpenidList())));

        //封装dingding
        JSONObject jsonObject = new JSONObject();
        if (alarmContacterInfoDto.getDingdingList() != null && alarmContacterInfoDto.getDingdingList().size() > 0) {
            jsonObject.put("dingdingList", JSONObject.toJSONString(alarmContacterInfoDto.getDingdingList()));
        }
        jsonObject.put("notifyAll", alarmContacterInfoDto.getNotifyAll());

        alarmContacter.setDingding(jsonObject.toJSONString());

        Integer now = DateUtil.getNowTime();
        alarmContacter.setUpdateTime(now);
        alarmContacterMapper.updateById(alarmContacter);
    }

    /**
     * 删除
     *
     * @param alarmContacterIdDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public void deleteAlarmContacter(AlarmContacterIdDto alarmContacterIdDto) {
        if (alarmContacterIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }
        alarmContacterMapper.deleteById(alarmContacterIdDto.getId(), alarmContacterIdDto.getMerId());
    }


    /**
     * 查询紧急联系人详情
     *
     * @param alarmContacterIdDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public AlarmContacterInfoVo findAlarmContacterInfo(AlarmContacterIdDto alarmContacterIdDto) {
        if (alarmContacterIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        AlarmContacter alarmContacter = alarmContacterMapper.selectById(alarmContacterIdDto.getId(), alarmContacterIdDto.getMerId());

        if (alarmContacter == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该紧急联系人不存在");
        }

        AlarmContacterInfoVo alarmContacterInfoVo = new AlarmContacterInfoVo();
        BeanUtils.copyProperties(alarmContacter, alarmContacterInfoVo);

        //电话转化成list
        alarmContacterInfoVo.setMobileList(JSONObject.parseArray(alarmContacter.getMobile(), String.class));

        //邮箱转化成list
        alarmContacterInfoVo.setMailList(JSONObject.parseArray(alarmContacter.getMail(), String.class));

        //openid转化成list
        alarmContacterInfoVo.setOpenidList(JSONObject.parseArray(alarmContacter.getOpenid(), String.class));


        //dingding化成list
        if (StringUtils.isNotBlank(alarmContacter.getDingding())) {
            JSONObject dingding = JSONObject.parseObject(alarmContacter.getDingding());
            if (dingding != null) {
                //是否@所有人
                alarmContacterInfoVo.setNotifyAll(dingding.getInteger("notifyAll"));
                //钉钉信息
                String dingdingStr = dingding.getString("dingdingList");
                if (StringUtils.isNotBlank(dingdingStr)) {
                    List<AlarmContacterInfoVo.DingDing> dingDingList = JSONObject.parseArray(dingdingStr, AlarmContacterInfoVo.DingDing.class);
                    alarmContacterInfoVo.setDingdingList(dingDingList);
                }
            }
        }
        return alarmContacterInfoVo;
    }

    /**
     * 查询紧急联系人功能的悠哉公众号图片二维码
     *
     * @param
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public AlarmContacterOpenidUrlVo getWxpubQrCode(Long merId) {
        AlarmContacterOpenidUrlVo alarmContacterOpenidVo = new AlarmContacterOpenidUrlVo();
        //随机生成6位数key,用来请求openid
        String random = Tools.random(6);
        alarmContacterOpenidVo.setParaKey(random);
        //运营商+随机6位数作为获取二维码图片的动态码
        String paraKey = merId + "_" + random;
        String qrCode = wxpubService.getWxpubQrCode(paraKey);
        alarmContacterOpenidVo.setOpenidUrl(qrCode);
        return alarmContacterOpenidVo;
    }

    /**
     * 查询紧急联系人功能的悠哉公众号openid
     *
     * @param
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public AlarmContacterOpenidVo getWxpubOpenid(AlarmContacterOpenidDto alarmContacterOpenidDto) {

        AlarmContacterOpenidVo alarmContacterOpenidVo = new AlarmContacterOpenidVo();

        String parakey = Tools.getStr(alarmContacterOpenidDto.getParakey());
        if (StringUtils.isBlank(parakey)) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "parakey不能为空");
        }

        String wxpub_openid_key = alarmContacterOpenidDto.getMerId() + "_" + parakey;

        String openid = (String) redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.WXPUB_OPENID.getKey(), wxpub_openid_key));

        alarmContacterOpenidVo.setOpenid(openid);

        return alarmContacterOpenidVo;

    }

    /**
     * 查询紧急联系人功能的如何查询钉钉机器人链接信息
     *
     * @param
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public AlarmContacterDingdingUrlVo getDingdingUrl() {
        AlarmContacterDingdingUrlVo alarmContacterDingdingUrlVo = new AlarmContacterDingdingUrlVo();
        String dingdingReceiveMsg = uzaiConsoleSysConfig.getDingdingReceiveMsg();
        alarmContacterDingdingUrlVo.setDingdingUrl(dingdingReceiveMsg);
        return alarmContacterDingdingUrlVo;
    }

}
